package com.hjieli.controller.api;

import java.io.IOException;
import java.io.PrintWriter;
import java.net.URLEncoder;
import java.util.Map;

import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.hjieli.controller.BaseController;
import com.hjieli.utils.WeixinUtil;

import me.chanjar.weixin.common.api.WxConsts;
import me.chanjar.weixin.common.exception.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpConfigStorage;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.api.WxMpUserService;
import me.chanjar.weixin.mp.bean.result.WxMpOAuth2AccessToken;
import me.chanjar.weixin.mp.bean.result.WxMpUser;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateData;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateMessage;

@Controller
@RequestMapping("api/weixin")
public class WeixinController  extends BaseController{

	  	@Autowired
	  	private WxMpService wxMpService;
		@Autowired
		private WxMpConfigStorage wxMpConfigStorage;
		
		@Value("${weixin.authorize.url}")
		private String authorize_url;
		
		@RequestMapping(value= {"getWeixinUser"}, method = {RequestMethod.POST,RequestMethod.GET})
		@ResponseBody
		public Map<String,Object> getWeixinUser(@RequestParam("code") String code) throws Exception {
			
			String errorno = "200";
			String msg = "成功获取openId";
			String data = "";
			WxMpOAuth2AccessToken wxMpOAuth2AccessToken;
		    try {
		        wxMpOAuth2AccessToken = wxMpService.oauth2getAccessToken(code);
		    } catch (WxErrorException e) {
		    	msg = "重新获取code";
		    	data = "";
		    	errorno = "201";
		    	return returnResult(errorno,msg,data);
		    }
		    
		    JsonObject weixinObj = new JsonObject();
		    
		    WxMpUser user = null;
		    try {
		        user = wxMpService.oauth2getUserInfo(wxMpOAuth2AccessToken,null);
		        Gson gson = new Gson();
		        String jsonStr = gson.toJson(user);
		        JsonObject userObj = JsonParser.parseString(jsonStr).getAsJsonObject();
		        
		        weixinObj.add("weixinUser", userObj);
		        if(!user.getSubscribe()) {
		        	msg = "用户未关注公众号";
				    errorno = "002";
		        }
		     
		    }catch (Exception e){
		        msg = "获取用户基本信息失败";
		    	errorno = "001";
		        return returnResult(errorno,msg,e.toString());
		    }
		 
		    data = weixinObj.toString();
		    return returnResult(errorno,msg,data);
		}
		
		/**
		 * 后端组装 jssdk config 配置信息
		 * @param url
		 * @return
		 * @throws WxErrorException
		 */
		@RequestMapping(value= {"getJsConfig"}, method = {RequestMethod.POST,RequestMethod.GET})
		@ResponseBody
		
		public Map<String,Object> getJsConfig(String url) throws WxErrorException {
			String errorno = "200";
			String msg = "成功获取jsConfig";
		    String JsapiTicket = wxMpService.getJsapiTicket();
		    String config = WeixinUtil.getJsapiTicketConfig(wxMpConfigStorage.getAppId(), JsapiTicket, url);
		    JsonElement jsonElement = JsonParser.parseString(config);
		    return returnResult(errorno,msg,jsonElement.getAsJsonObject().toString());
		}
		
		
		
		/**
		 * 根据openId 获取用户相关信息
		 * @param openId
		 * @return
		 * @throws Exception
		 */
		@RequestMapping(value = {"getUserInfoByOpenId"}, method = {RequestMethod.GET,RequestMethod.GET})
		@ResponseBody
		public Map<String,Object> getUserInfoByOpenId(@RequestParam("openId") String openId) throws Exception{
			String errorno = "200";
			String msg = "成功获取用户信息";
			WxMpUser wxMpUser;
			WxMpUserService wxMpUserService = wxMpService.getUserService();
			wxMpUser = wxMpUserService.userInfo(openId);
			JsonObject obj = new JsonObject();
			Gson gson = new Gson();
		    String jsonStr = gson.toJson(wxMpUser);
		    JsonObject wxMpUserObj = JsonParser.parseString(jsonStr).getAsJsonObject();
		   
	        if(!wxMpUser.getSubscribe()) {
	        	msg = "用户未关注公众号";
			    errorno = "000";
	        }
			obj.add("weixinInfo",wxMpUserObj);
			return returnResult(errorno,msg,obj.toString());
		}
		
		/**
		 * 微信授权地址
		 * @param returnUrl
		 * @param request
		 * @return
		 */
		@RequestMapping(value = {"authorize"}, method = {RequestMethod.POST,RequestMethod.GET})
		@ResponseBody
		public String authorize(@RequestParam("returnUrl") String returnUrl,
						   HttpServletRequest request){
//			String authorUrl = request.getSession().getServletContext().getInitParameter("getOpenIdUrl");
			String redirectURL = wxMpService.oauth2buildAuthorizationUrl(authorize_url, WxConsts.OAuth2Scope.SNSAPI_USERINFO, URLEncoder.encode(returnUrl));
			return redirectURL;
		}
		
		/**
		 * 获取授权成功后 返回的openId
		 * @param code
		 * @param returnUrl
		 * @param request
		 * @param response
		 * @return
		 * @throws Exception
		 */
		@RequestMapping(value = {"getOpenId"}, method = {RequestMethod.POST,RequestMethod.GET})
		public String getCode(@RequestParam("code") String code,
							  @RequestParam("state") String returnUrl,
							  HttpServletRequest request
				,HttpServletResponse response) throws Exception{
			WxMpOAuth2AccessToken wxMpOAuth2AccessToken;
	        try {
	            wxMpOAuth2AccessToken = wxMpService.oauth2getAccessToken(code);
	        } catch (WxErrorException e) {
	            
	            throw new Exception(e.getError().getErrorMsg());
	        }
	        String openId = wxMpOAuth2AccessToken.getOpenId();
			return "redirect:" + returnUrl + "?openId=" + openId;
		}
		
		@RequestMapping(value = {"token"}, method = {RequestMethod.GET,RequestMethod.POST})
		public void token(
				PrintWriter out, 
				HttpServletRequest request,
				HttpServletResponse response, 
				@RequestParam(value = "signature", required = false) String signature,
				@RequestParam String timestamp,
				@RequestParam String nonce,
				@RequestParam String echostr) throws Exception{
			String method = request.getMethod().toString().toLowerCase();
			if(method.equals("get")) {
				if (wxMpService.checkSignature(timestamp, nonce, signature)) {
		           out.print(echostr);
				}
			} else if(method.equals("post")) {
		//				WxMpXmlMessage wxMpXmlMessage = WxMpXmlMessage.fromEncryptedXml(readContent(request), wxMpConfigStorage, timestamp, nonce, signature);
		//				WxMpXmlMessage wxMpXmlMessage = WxMpXmlMessage.fromXml(readContent(request));
		//				String content = wxMpXmlMessage.getContent();
		//				String toUser = wxMpXmlMessage.getToUser();
		//				String fromUser = wxMpXmlMessage.getFromUser();
		//				if(content.equals(CSDN_LOGIN_QRCODE)) {
		//					 
		//					WxMpXmlOutMessage wxMpXmlOutMessage = WxMpXmlOutMessage.IMAGE()
		//	                        .fromUser(toUser)
		//	                        .toUser(fromUser)
		//	                        .build();
		//					
		//					 String outXml = wxMpXmlOutMessage.toXml();
		//	                 System.out.println(outXml);
		//	                 response.getWriter().write(outXml);
		//				}
				
			}
			
			
		}
		
		@RequestMapping(value = {"testWeixinMsg"}, method = {RequestMethod.GET})
		@ResponseBody
		public Map<String,Object> testWeixinMsg() throws Exception{
			WxMpTemplateMessage templateMessage = WxMpTemplateMessage.builder()
					.toUser("oTz641EOpb6hJw-SRHb7wf8Rtirk")
					.templateId("9o5LSKJRbn4_ju6TS3wYFcsIO5ABYSnlhQ3XaIxHVes")
					.url("http://www.hjieli.com/weekframe/upload/login-qrcode.png")
					.build();
			
			templateMessage.addWxMpTemplateData(new WxMpTemplateData("first","亲爱的用户，您申请的下载服务进度如下","#000000"));
			templateMessage.addWxMpTemplateData(new WxMpTemplateData("keyword1","申请CSDN下载服务","#000000"));
			templateMessage.addWxMpTemplateData(new WxMpTemplateData("keyword2","提交成功","#000000"));
			templateMessage.addWxMpTemplateData(new WxMpTemplateData("keyword3","1-2小时之内反馈","#000000"));
			templateMessage.addWxMpTemplateData(new WxMpTemplateData("remark","如有疑问请联系微信号 wxhslhj","#FF0000"));
			
			wxMpService.getTemplateMsgService().sendTemplateMsg(templateMessage);
			
			
			String errorno = "200";
			String msg = "成功获取用户信息";
			 HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes())
		             .getRequest();
			
			return returnResult(errorno,msg,request.getServletContext().getRealPath("upload"));
		}
		
		private String readContent(HttpServletRequest request) throws IOException {
		    ServletInputStream sis = request.getInputStream();
		    // 取HTTP请求流长度
		    int size = request.getContentLength();
		    // 用于缓存每次读取的数据
		    byte[] buffer = new byte[size];
		    // 用于存放结果的数组
		    byte[] xmldataByte = new byte[size];
		    int count = 0;
		    int rbyte = 0;
		    // 循环读取
		    while (count < size) {
		        // 每次实际读取长度存于rbyte中
		        rbyte = sis.read(buffer);
		        for (int i = 0; i < rbyte; i++) {
		            xmldataByte[count + i] = buffer[i];
		        }
		        count += rbyte;
		    }
		    return new String(xmldataByte, "UTF-8");
		}

}
